package model

import (
	"common/global"
	"time"
)

type OrderBargain struct {
	Id           int64     `gorm:"column:id;type:bigint;comment:主键ID;primaryKey;not null;" json:"id"`                                   // 主键ID
	OrderId      int64     `gorm:"column:order_id;type:bigint;comment:关联主订单ID;not null;" json:"order_id"`                               // 关联主订单ID
	ActivityId   int64     `gorm:"column:activity_id;type:mediumint;comment:砍价活动ID;not null;" json:"activity_id"`                       // 砍价活动ID
	CurrentPrice float32   `gorm:"column:current_price;type:decimal(8, 2);comment:当前砍价价格;not null;" json:"current_price"`               // 当前砍价价格
	CurrentCuts  int64     `gorm:"column:current_cuts;type:int;comment:当前已砍次数（含发起者自己）;not null;default:1;" json:"current_cuts"`         // 当前已砍次数（含发起者自己）
	Status       int64     `gorm:"column:status;type:tinyint;comment:砍价状态：0=砍价中，1=砍价成功，2=砍价失败，3=已过期;not null;default:0;" json:"status"` // 砍价状态：0=砍价中，1=砍价成功，2=砍价失败，3=已过期
	ExpireTime   time.Time `gorm:"column:expire_time;type:datetime;comment:砍价有效期;not null;" json:"expire_time"`                         // 砍价有效期
	CreatedAt    time.Time `gorm:"column:created_at;type:datetime;comment:创建时间;not null;" json:"created_at"`                            // 创建时间
	UpdatedAt    time.Time `gorm:"column:updated_at;type:datetime;comment:更新时间;not null;" json:"updated_at"`                            // 更新时间
}

func (m *OrderBargain) TableName() string {
	return "order_bargain"
}

func OrderBargainCreate(bargain *OrderBargain) error {
	return global.Db.Model(&OrderBargain{}).Create(bargain).Error
}

func ExistBargain(orderId, activityId int64) (result *OrderBargain, err error) {
	err = global.Db.Model(&OrderBargain{}).Where("order_id =? AND activity_id =? AND status = 0", orderId, activityId).First(&result).Error
	if err != nil {
		return nil, err
	}
	return result, nil
}

func GetOrderBargainInfo(orderId int64) (result *OrderBargain, err error) {
	err = global.Db.Model(&OrderBargain{}).Where("order_id =?", orderId).Limit(1).Find(&result).Error
	if err != nil {
		return nil, err
	}
	return result, nil
}

func SaveOrderBargain(orderBargainInfo *OrderBargain) error {
	err := global.Db.Model(&OrderBargain{}).Where("id =?", orderBargainInfo.Id).Save(orderBargainInfo).Error
	return err
}
